﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CounterServerModel;
using System.Data;
using CounterServerModel.Authentication;

namespace SmartCounters
{
	public partial class UserManagement : System.Web.UI.Page
	{

		DataTable usersTable;


		protected void Page_Load(object sender, EventArgs e)
		{
			((MainTemplate)Master).m_PagePermissionFilter = MainTemplate.k_AdminPageFilter;
		}

		protected void Page_Prerender(object sender, EventArgs e)
		{
			InformationReader infoProvider = new InformationReader();

			usersTable = new InformationReader().GetUsersDataTable(((MainTemplate)Master).AuthenticatedLoggedInUserCredentials);
			BindGrid();
		}

		protected void EditCommand(object sender, DataGridCommandEventArgs e)
		{
			int UserID;
			int.TryParse(e.Item.Cells[2].Text, out UserID);
			
			UserInfo userToEdit = new InformationReader().GetUserInformation(((MainTemplate)Master).AuthenticatedLoggedInUserCredentials,UserID);

			Session[UserDetails.k_UserSessionKey] = userToEdit;

			if (!Page.ClientScript.IsStartupScriptRegistered("openForm"))
			{
				ScriptManager.RegisterStartupScript(
					UserManagementUpdatePanel, 
					UserManagementUpdatePanel.GetType(),
					"openForm",
					"openUserDetailsForm();", 
					true);
			}
		}

		protected void ItemCommand(object sender, DataGridCommandEventArgs e)
		{
			switch (e.CommandName)
			{
				case "DeleteCommand":
					DeleteItem(e);
				break;

				default:
					// Do nothing.
				break;
			}

		}

		private void DeleteItem(DataGridCommandEventArgs e)
		{
			int UserID;
			int.TryParse(e.Item.Cells[2].Text, out UserID);

			InformationUpdater updateProvider = new InformationUpdater();
			updateProvider.DeleteUser(((MainTemplate)Master).AuthenticatedLoggedInUserCredentials, UserID);
		}

		private void BindGrid()
		{
			UsersGrid.DataSource = usersTable;
			UsersGrid.ItemDataBound += Item_Bound;
			UsersGrid.DataBind();
		}

		void Item_Bound(Object sender, DataGridItemEventArgs e)
		{
			// Culomn Row Index should be ignored
			if (e.Item.ItemIndex == -1)
				return;

			// If in Edit Mode Ignore Bound Event
			if (UsersGrid.EditItemIndex == e.Item.ItemIndex)
				return;
			
			TableCell permissionCell = e.Item.Cells[4];
			eUserPermissions permission = (eUserPermissions)int.Parse(permissionCell.Text);
			permissionCell.Text = permission.ToString();
		}

	}
}